package com.it.product.helper;

import com.spzx.product.api.domain.vo.CategoryVo;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * projectName: spzx-parent
 *
 * @author: 王宝贵
 * time: 2024/10/8 20:38 周二
 * description:  TODO 将集合装换为树结构工具类
 */

public class CategoryHelper {


    public static List<CategoryVo> buildTree(List<CategoryVo> categoryVoList) {

        List<CategoryVo> categoryVoTree =new ArrayList<>();
        //非空
        if(!CollectionUtils.isEmpty(categoryVoList)){
            for (CategoryVo categoryVo : categoryVoList) {
                if(categoryVo.getParentId().intValue() ==0){
                    //找到所有的一级分类
                    categoryVoTree.add(findChildren(categoryVo,categoryVoList));
                }
            }
        }

        return categoryVoTree;
    }

    private static CategoryVo findChildren(CategoryVo categoryVo, List<CategoryVo> categoryVoList) {
        //先初始化集合 防止空指针异常
        categoryVo.setChildren(new ArrayList<>());

        for (CategoryVo vo : categoryVoList) {
            if(categoryVo.getId().intValue() ==vo.getParentId().intValue()){
                //如果有子类
                 vo = findChildren(vo, categoryVoList);

                 categoryVo.getChildren().add(vo);
            }
        }

        return categoryVo;


    }
}